/*
  需求：给整个页面添加背景水印。

  思路：
    1、使用 canvas 特性生成 base64 格式的图片文件，设置其字体大小，颜色等。
    2、将其设置为背景图片，从而实现页面或组件水印效果
  
  使用：设置水印文案，颜色，字体大小即可
  <div v-waterMarker="{text:'版权所有',textColor:'rgba(180, 180, 180, 0.4)'}"></div>
*/

import type { Directive, DirectiveBinding } from "vue";

const addWaterMarker = (
  str: string,
  parentNode: HTMLElement,
  font: string = "16px Microsoft JhengHei",
  textColor: string = "rgba(180, 180, 180, 0.3)"
): void => {
  // 创建水印层
  const waterMarkerDiv = document.createElement("div");

  // 设置水印层样式
  waterMarkerDiv.style.position = "absolute";
  waterMarkerDiv.style.top = "0";
  waterMarkerDiv.style.left = "0";
  waterMarkerDiv.style.width = "100%";
  waterMarkerDiv.style.height = "100%";
  waterMarkerDiv.style.pointerEvents = "none"; // 避免干扰点击事件
  waterMarkerDiv.style.zIndex = "9999"; // 保证水印在最上层
  waterMarkerDiv.style.overflow = "hidden";

  // 创建 canvas 绘制水印内容
  const canvas = document.createElement("canvas");
  canvas.width = 300; // 调整宽度
  canvas.height = 200; // 调整高度
  const ctx = canvas.getContext("2d");
  if (ctx) {
    ctx.rotate((-20 * Math.PI) / 180); // 旋转水印
    ctx.font = font;
    ctx.fillStyle = textColor;
    ctx.textAlign = "left";
    ctx.textBaseline = "middle";
    ctx.fillText(str, canvas.width / 10, canvas.height / 2);
  }

  // 将生成的水印内容设置为水印层的背景
  waterMarkerDiv.style.backgroundImage = `url(${canvas.toDataURL("image/png")})`;

  // 确保父元素有定位，否则无法正确覆盖
  const parentStyle = getComputedStyle(parentNode);
  if (parentStyle.position === "static" || !parentStyle.position) {
    parentNode.style.position = "relative";
  }

  // 将水印层添加到父元素
  parentNode.appendChild(waterMarkerDiv);
};

const waterMarker: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { text, font, textColor } = binding.value || {};
    addWaterMarker(text || "默认水印", el, font, textColor);
  }
};

export default waterMarker;
